/**
 * 监控面板JavaScript模块
 * 提供实时数据更新、图表管理、WebSocket连接等功能
 */

class DashboardManager {
    constructor() {
        this.charts = {};
        this.websocket = null;
        this.autoRefreshInterval = null;
        this.isAutoRefreshEnabled = false;
        this.currentTimeRange = 1; // 默认1小时
        this.lastUpdateTime = null;
        
        this.init();
    }
    
    init() {
        this.initEventListeners();
        this.loadInitialData();
        this.connectWebSocket();
    }
    
    initEventListeners() {
        // 刷新按钮
        $('#refresh-btn').on('click', () => this.refreshData());
        
        // 自动刷新切换
        $('#auto-refresh-toggle').on('click', () => this.toggleAutoRefresh());
        
        // 时间范围选择
        $('.time-range-option').on('click', (e) => {
            const hours = $(e.target).data('hours');
            this.changeTimeRange(hours);
        });
        
        // 页面可见性变化
        document.addEventListener('visibilitychange', () => {
            if (document.hidden) {
                this.pauseUpdates();
            } else {
                this.resumeUpdates();
            }
        });
        
        // 窗口大小变化
        $(window).on('resize', () => {
            this.resizeCharts();
        });
    }
    
    async loadInitialData() {
        try {
            this.showLoading();
            const response = await this.fetchDashboardData();
            
            if (response.success) {
                this.updateDashboard(response.data);
                this.lastUpdateTime = new Date();
                this.updateLastRefreshTime();
            } else {
                this.showError('加载监控数据失败: ' + response.message);
            }
        } catch (error) {
            console.error('加载初始数据失败:', error);
            this.showError('加载监控数据失败');
        } finally {
            this.hideLoading();
        }
    }
    
    async fetchDashboardData() {
        const params = new URLSearchParams({
            time_range: this.currentTimeRange,
            refresh: 'true'
        });
        
        const response = await fetch(`/api/v1/dashboard/data?${params}`);
        return await response.json();
    }
    
    updateDashboard(data) {
        this.updateSystemMetrics(data.system);
        this.updateStrategyMetrics(data.strategies);
        this.updateAlertMetrics(data.alerts);
        this.updateCharts(data);
        this.updateStrategyList(data.strategies?.strategies || []);
        this.updateAlertList(data.alerts?.active_alerts || []);
    }
    
    updateSystemMetrics(systemData) {
        if (!systemData?.current) return;
        
        const current = systemData.current;
        
        this.updateMetricCard('cpu-usage', current.cpu_percent, '%', 'cpu');
        this.updateMetricCard('memory-usage', current.memory_percent, '%', 'memory');
        this.updateMetricCard('disk-usage', current.disk_percent, '%', 'disk');
        this.updateMetricCard('network-io', current.network_io, 'MB/s', 'network');
    }
    
    updateStrategyMetrics(strategyData) {
        if (!strategyData?.summary) return;
        
        const summary = strategyData.summary;
        
        this.updateMetricCard('active-strategies', summary.active_strategies, '个', 'strategies');
        this.updateMetricCard('total-profit', summary.total_profit, '', 'profit', true);
        this.updateMetricCard('avg-win-rate', summary.avg_win_rate * 100, '%', 'winrate');
        this.updateMetricCard('total-trades', summary.total_trades, '笔', 'trades');
    }
    
    updateAlertMetrics(alertData) {
        if (!alertData?.stats) return;
        
        const stats = alertData.stats;
        
        this.updateMetricCard('active-alerts', stats.active_count, '个', 'alerts');
        this.updateMetricCard('critical-alerts', stats.critical_count, '个', 'critical');
    }
    
    updateMetricCard(elementId, value, suffix, type, isCurrency = false) {
        const element = $(`#${elementId}`);
        if (!element.length) return;
        
        let formattedValue;
        if (isCurrency) {
            formattedValue = this.formatCurrency(value);
        } else if (typeof value === 'number') {
            formattedValue = value.toFixed(type === 'cpu' || type === 'memory' ? 1 : 0) + suffix;
        } else {
            formattedValue = value + suffix;
        }
        
        // 添加数据更新动画
        element.addClass('data-updated');
        element.text(formattedValue);
        
        setTimeout(() => {
            element.removeClass('data-updated');
        }, 500);
        
        // 更新趋势指示器
        this.updateTrendIndicator(elementId, value, type);
    }
    
    updateTrendIndicator(elementId, currentValue, type) {
        const trendElement = $(`#${elementId}-trend`);
        if (!trendElement.length) return;
        
        // 这里可以实现趋势计算逻辑
        // 暂时省略具体实现
    }
    
    updateCharts(data) {
        if (data.system?.chart_data) {
            this.updateSystemChart(data.system.chart_data);
        }
        
        if (data.strategies?.strategies) {
            this.updateProfitChart(data.strategies.strategies);
            this.updatePerformanceChart(data.strategies.performance_data);
        }
        
        if (data.alerts?.trend_data) {
            this.updateAlertTrendChart(data.alerts.trend_data);
        }
    }
    
    updateSystemChart(chartData) {
        if (!chartData.timestamps || chartData.timestamps.length === 0) {
            return;
        }
        
        const labels = chartData.timestamps.map(ts => {
            const date = new Date(ts);
            return date.toLocaleTimeString('zh-CN', { 
                hour: '2-digit', 
                minute: '2-digit' 
            });
        });
        
        if (!this.charts.system) {
            this.initSystemChart();
        }
        
        this.charts.system.data.labels = labels;
        this.charts.system.data.datasets[0].data = chartData.cpu;
        this.charts.system.data.datasets[1].data = chartData.memory;
        this.charts.system.data.datasets[2].data = chartData.disk;
        
        this.charts.system.update('none'); // 无动画更新
    }
    
    updateProfitChart(strategies) {
        const labels = [];
        const data = [];
        const colors = ['#4e73df', '#1cc88a', '#36b9cc', '#f6c23e', '#e74a3b'];
        
        strategies.forEach((strategy, index) => {
            if (strategy.total_profit !== 0) {
                labels.push(strategy.name);
                data.push(Math.abs(strategy.total_profit));
            }
        });
        
        if (labels.length === 0) {
            labels.push('暂无数据');
            data.push(1);
        }
        
        if (!this.charts.profit) {
            this.initProfitChart();
        }
        
        this.charts.profit.data.labels = labels;
        this.charts.profit.data.datasets[0].data = data;
        this.charts.profit.data.datasets[0].backgroundColor = colors.slice(0, data.length);
        
        this.charts.profit.update();
    }
    
    updatePerformanceChart(performanceData) {
        if (!performanceData || !this.charts.performance) return;
        
        // 更新性能图表逻辑
        // 暂时省略具体实现
    }
    
    updateAlertTrendChart(trendData) {
        if (!trendData || !this.charts.alertTrend) return;
        
        // 更新告警趋势图表逻辑
        // 暂时省略具体实现
    }
    
    initSystemChart() {
        const ctx = document.getElementById('systemChart');
        if (!ctx) return;
        
        this.charts.system = new Chart(ctx, {
            type: 'line',
            data: {
                labels: [],
                datasets: [{
                    label: 'CPU使用率',
                    data: [],
                    borderColor: '#4e73df',
                    backgroundColor: 'rgba(78, 115, 223, 0.1)',
                    tension: 0.3,
                    fill: true
                }, {
                    label: '内存使用率',
                    data: [],
                    borderColor: '#1cc88a',
                    backgroundColor: 'rgba(28, 200, 138, 0.1)',
                    tension: 0.3,
                    fill: true
                }, {
                    label: '磁盘使用率',
                    data: [],
                    borderColor: '#36b9cc',
                    backgroundColor: 'rgba(54, 185, 204, 0.1)',
                    tension: 0.3,
                    fill: true
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                interaction: {
                    intersect: false,
                    mode: 'index'
                },
                scales: {
                    x: {
                        display: true,
                        title: {
                            display: true,
                            text: '时间'
                        }
                    },
                    y: {
                        display: true,
                        title: {
                            display: true,
                            text: '使用率 (%)'
                        },
                        min: 0,
                        max: 100
                    }
                },
                plugins: {
                    legend: {
                        display: true,
                        position: 'top'
                    },
                    tooltip: {
                        backgroundColor: 'rgba(0, 0, 0, 0.8)',
                        titleColor: 'white',
                        bodyColor: 'white',
                        borderColor: 'rgba(255, 255, 255, 0.1)',
                        borderWidth: 1
                    }
                },
                animation: {
                    duration: 750,
                    easing: 'easeInOutQuart'
                }
            }
        });
    }
    
    initProfitChart() {
        const ctx = document.getElementById('profitChart');
        if (!ctx) return;
        
        this.charts.profit = new Chart(ctx, {
            type: 'doughnut',
            data: {
                labels: [],
                datasets: [{
                    data: [],
                    backgroundColor: [
                        '#4e73df',
                        '#1cc88a',
                        '#36b9cc',
                        '#f6c23e',
                        '#e74a3b'
                    ],
                    borderWidth: 2,
                    borderColor: '#ffffff'
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        position: 'bottom',
                        labels: {
                            padding: 20,
                            usePointStyle: true
                        }
                    },
                    tooltip: {
                        backgroundColor: 'rgba(0, 0, 0, 0.8)',
                        titleColor: 'white',
                        bodyColor: 'white',
                        callbacks: {
                            label: (context) => {
                                const label = context.label || '';
                                const value = this.formatCurrency(context.parsed);
                                return `${label}: ${value}`;
                            }
                        }
                    }
                },
                animation: {
                    animateRotate: true,
                    animateScale: true
                }
            }
        });
    }
    
    updateStrategyList(strategies) {
        const container = $('#strategy-status');
        
        if (strategies.length === 0) {
            container.html('<div class="empty-state"><i class="fas fa-robot"></i><p>暂无策略</p></div>');
            return;
        }
        
        let html = '<div class="table-responsive"><table class="table table-sm strategy-status-table">';
        html += '<thead><tr><th>策略名称</th><th>状态</th><th>收益</th><th>胜率</th></tr></thead><tbody>';
        
        strategies.slice(0, 5).forEach(strategy => {
            const statusClass = this.getStrategyStatusClass(strategy.status);
            const statusText = this.getStatusText(strategy.status);
            const profitClass = strategy.total_profit >= 0 ? 'profit-positive' : 'profit-negative';
            
            html += `
                <tr class="strategy-item">
                    <td>
                        <strong>${strategy.name}</strong>
                        <br><small class="text-muted">${strategy.symbol}</small>
                    </td>
                    <td><span class="badge ${statusClass}">${statusText}</span></td>
                    <td class="${profitClass}">${this.formatCurrency(strategy.total_profit)}</td>
                    <td>${(strategy.win_rate * 100).toFixed(1)}%</td>
                </tr>
            `;
        });
        
        html += '</tbody></table></div>';
        
        if (strategies.length > 5) {
            html += `<div class="text-center mt-2">
                <a href="/strategies" class="btn btn-sm btn-outline-primary">
                    查看全部 ${strategies.length} 个策略
                </a>
            </div>`;
        }
        
        container.html(html);
    }
    
    updateAlertList(alerts) {
        const container = $('#recent-alerts');
        
        if (alerts.length === 0) {
            container.html('<div class="empty-state"><i class="fas fa-bell"></i><p>暂无告警</p></div>');
            return;
        }
        
        let html = '<div class="list-group list-group-flush">';
        
        alerts.slice(0, 5).forEach(alert => {
            const levelClass = this.getAlertLevelClass(alert.level);
            const levelIcon = this.getAlertLevelIcon(alert.level);
            const timeAgo = this.getTimeAgo(alert.created_at);
            
            html += `
                <div class="list-group-item alert-item alert-${alert.level}">
                    <div class="d-flex w-100 justify-content-between">
                        <h6 class="mb-1">
                            <i class="${levelIcon} ${levelClass} me-2"></i>
                            ${alert.title}
                        </h6>
                        <small class="text-muted">${timeAgo}</small>
                    </div>
                    <p class="mb-1 small">${alert.message}</p>
                    ${alert.strategy_name ? `<small class="text-muted">策略: ${alert.strategy_name}</small>` : ''}
                </div>
            `;
        });
        
        html += '</div>';
        
        if (alerts.length > 5) {
            html += `<div class="text-center mt-2">
                <a href="/alerts" class="btn btn-sm btn-outline-primary">
                    查看全部 ${alerts.length} 个告警
                </a>
            </div>`;
        }
        
        container.html(html);
    }
    
    connectWebSocket() {
        const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
        const wsUrl = `${protocol}//${window.location.hostname}:8765`;
        
        try {
            this.websocket = new WebSocket(wsUrl);
            
            this.websocket.onopen = () => {
                console.log('WebSocket连接已建立');
                this.showWebSocketStatus('connected', '实时数据连接已建立');
                
                // 订阅数据频道
                this.websocket.send(JSON.stringify({
                    type: 'subscribe',
                    channels: ['dashboard', 'system', 'strategies', 'alerts']
                }));
            };
            
            this.websocket.onmessage = (event) => {
                try {
                    const message = JSON.parse(event.data);
                    this.handleWebSocketMessage(message);
                } catch (error) {
                    console.error('解析WebSocket消息失败:', error);
                }
            };
            
            this.websocket.onclose = () => {
                console.log('WebSocket连接已断开');
                this.showWebSocketStatus('disconnected', '实时数据连接已断开，正在重连...');
                
                // 5秒后重连
                setTimeout(() => this.connectWebSocket(), 5000);
            };
            
            this.websocket.onerror = (error) => {
                console.error('WebSocket连接错误:', error);
                this.showWebSocketStatus('error', '实时数据连接失败');
            };
            
        } catch (error) {
            console.warn('WebSocket连接失败:', error);
            this.showWebSocketStatus('error', 'WebSocket不可用');
        }
    }
    
    handleWebSocketMessage(message) {
        switch (message.type) {
            case 'data':
                if (message.channel === 'dashboard') {
                    this.updateDashboard(message.data);
                    this.lastUpdateTime = new Date();
                    this.updateLastRefreshTime();
                }
                break;
                
            case 'notification':
                this.showNotification(message.title, message.message, message.level);
                break;
                
            case 'alert':
                this.handleNewAlert(message.data);
                break;
                
            default:
                console.log('未知WebSocket消息类型:', message.type);
        }
    }
    
    handleNewAlert(alertData) {
        // 显示新告警通知
        this.showNotification(
            '新告警',
            `${alertData.title}: ${alertData.message}`,
            alertData.level
        );
        
        // 更新告警计数
        const currentCount = parseInt($('#active-alerts').text()) || 0;
        this.updateMetricCard('active-alerts', currentCount + 1, '个', 'alerts');
    }
    
    showWebSocketStatus(status, message) {
        const statusElement = $('#websocket-status');
        const messageElement = $('#websocket-message');
        
        statusElement.removeClass('websocket-connected websocket-disconnected websocket-error');
        statusElement.addClass(`websocket-${status}`);
        
        messageElement.text(message);
        statusElement.show();
        
        if (status === 'connected') {
            setTimeout(() => statusElement.fadeOut(), 3000);
        }
    }
    
    refreshData() {
        this.loadInitialData();
    }
    
    toggleAutoRefresh() {
        if (this.isAutoRefreshEnabled) {
            this.stopAutoRefresh();
        } else {
            this.startAutoRefresh();
        }
    }
    
    startAutoRefresh() {
        this.isAutoRefreshEnabled = true;
        this.autoRefreshInterval = setInterval(() => {
            if (!document.hidden) {
                this.loadInitialData();
            }
        }, 30000); // 30秒刷新一次
        
        $('#auto-refresh-toggle').addClass('auto-refresh-active');
        $('#auto-refresh-icon').removeClass('fa-play').addClass('fa-pause');
        $('#auto-refresh-text').text('关闭自动刷新');
    }
    
    stopAutoRefresh() {
        this.isAutoRefreshEnabled = false;
        if (this.autoRefreshInterval) {
            clearInterval(this.autoRefreshInterval);
            this.autoRefreshInterval = null;
        }
        
        $('#auto-refresh-toggle').removeClass('auto-refresh-active');
        $('#auto-refresh-icon').removeClass('fa-pause').addClass('fa-play');
        $('#auto-refresh-text').text('开启自动刷新');
    }
    
    changeTimeRange(hours) {
        this.currentTimeRange = hours;
        $('.time-range-option').removeClass('active');
        $(`.time-range-option[data-hours="${hours}"]`).addClass('active');
        this.loadInitialData();
    }
    
    pauseUpdates() {
        if (this.websocket && this.websocket.readyState === WebSocket.OPEN) {
            this.websocket.send(JSON.stringify({
                type: 'pause'
            }));
        }
    }
    
    resumeUpdates() {
        if (this.websocket && this.websocket.readyState === WebSocket.OPEN) {
            this.websocket.send(JSON.stringify({
                type: 'resume'
            }));
        }
        
        // 恢复时刷新数据
        this.loadInitialData();
    }
    
    resizeCharts() {
        Object.values(this.charts).forEach(chart => {
            if (chart && typeof chart.resize === 'function') {
                chart.resize();
            }
        });
    }
    
    updateLastRefreshTime() {
        if (this.lastUpdateTime) {
            const timeStr = this.lastUpdateTime.toLocaleTimeString('zh-CN');
            $('#last-refresh-time').text(`最后更新: ${timeStr}`);
        }
    }
    
    showLoading() {
        $('.loading-overlay').show();
    }
    
    hideLoading() {
        $('.loading-overlay').hide();
    }
    
    showError(message) {
        this.showNotification('错误', message, 'error');
    }
    
    showSuccess(message) {
        this.showNotification('成功', message, 'success');
    }
    
    showNotification(title, message, level = 'info') {
        const alertClass = level === 'error' ? 'danger' : level;
        const iconClass = this.getNotificationIcon(level);
        
        const notification = `
            <div class="alert alert-${alertClass} alert-dismissible fade show notification-alert" role="alert">
                <i class="${iconClass} me-2"></i>
                <strong>${title}</strong> ${message}
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        `;
        
        $('main').prepend(notification);
        
        // 5秒后自动消失
        setTimeout(() => {
            $('.notification-alert').first().fadeOut(() => {
                $(this).remove();
            });
        }, 5000);
    }
    
    getNotificationIcon(level) {
        const iconMap = {
            'success': 'fas fa-check-circle',
            'info': 'fas fa-info-circle',
            'warning': 'fas fa-exclamation-triangle',
            'error': 'fas fa-times-circle'
        };
        return iconMap[level] || 'fas fa-info-circle';
    }
    
    getStrategyStatusClass(status) {
        const classMap = {
            'running': 'bg-success',
            'stopped': 'bg-secondary',
            'error': 'bg-danger',
            'paused': 'bg-warning'
        };
        return classMap[status] || 'bg-secondary';
    }
    
    getStatusText(status) {
        const statusMap = {
            'running': '运行中',
            'stopped': '已停止',
            'error': '错误',
            'paused': '已暂停'
        };
        return statusMap[status] || status;
    }
    
    getAlertLevelClass(level) {
        const classMap = {
            'info': 'alert-level-info',
            'warning': 'alert-level-warning',
            'error': 'alert-level-error',
            'critical': 'alert-level-critical'
        };
        return classMap[level] || 'alert-level-info';
    }
    
    getAlertLevelIcon(level) {
        const iconMap = {
            'info': 'fas fa-info-circle',
            'warning': 'fas fa-exclamation-triangle',
            'error': 'fas fa-times-circle',
            'critical': 'fas fa-exclamation-circle'
        };
        return iconMap[level] || 'fas fa-info-circle';
    }
    
    formatCurrency(amount) {
        return new Intl.NumberFormat('zh-CN', {
            style: 'currency',
            currency: 'CNY',
            minimumFractionDigits: 2,
            maximumFractionDigits: 2
        }).format(amount);
    }
    
    getTimeAgo(timestamp) {
        const now = new Date();
        const time = new Date(timestamp);
        const diff = now - time;
        
        const seconds = Math.floor(diff / 1000);
        const minutes = Math.floor(diff / 60000);
        const hours = Math.floor(diff / 3600000);
        const days = Math.floor(diff / 86400000);
        
        if (days > 0) return `${days}天前`;
        if (hours > 0) return `${hours}小时前`;
        if (minutes > 0) return `${minutes}分钟前`;
        if (seconds > 30) return `${seconds}秒前`;
        return '刚刚';
    }
    
    destroy() {
        // 清理资源
        if (this.websocket) {
            this.websocket.close();
        }
        
        if (this.autoRefreshInterval) {
            clearInterval(this.autoRefreshInterval);
        }
        
        Object.values(this.charts).forEach(chart => {
            if (chart && typeof chart.destroy === 'function') {
                chart.destroy();
            }
        });
        
        this.charts = {};
    }
}

// 全局实例
let dashboardManager = null;

// 页面加载完成后初始化
$(document).ready(function() {
    dashboardManager = new DashboardManager();
});

// 页面卸载时清理资源
$(window).on('beforeunload', function() {
    if (dashboardManager) {
        dashboardManager.destroy();
    }
});

// 导出给其他模块使用
window.DashboardManager = DashboardManager;